<?php

declare(strict_types=1);

namespace app\api\middleware;

use app\common\Token;

class Auth
{
    /**
     * 处理请求
     * 利用jwt验证token中间件
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {
        $white_list  = [
            '/api/auth/login',
        ];

        $request_uri = $_SERVER['REQUEST_URI'];
        $pathinfo    = explode('?', $request_uri)[0];
        $pathinfo    = strtolower($pathinfo);

        //排除白名单
        if (!in_array($pathinfo, $white_list)) {
            //验证登录
            if (!$request->header('token')) {
                return json(['code' => 302, 'msg' => 'token不存在']);
            }

            $token = $request->header('token');

            if (Token::verifyToken($token)) {
                $data = Token::getDataByToken($token);

                if ($data['code'] == 200) {
                    $uid = (array)$data['data']['data'];
                    $uid = $uid['uid'];
                    $request->uid = $uid;
                } else {
                    return json(['code' => 302, 'msg' => $data['msg'],]);
                }

                return $next($request);
            } else {
                return json(['code' => 302, 'msg' => 'token有误']);
            }
        }
        return $next($request);
    }
}
